import React, { useState, useEffect } from 'react'
import { Input, Row, Col, Empty, Spin, Button, Modal, Form, Input as AntdInput, message } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { Character, CharacterCreate } from '../types';
import CharacterCard from './CharacterCard';
import characterService from '../services/characterService';

const { Search } = Input;

interface CharacterSearchProps {
  onCharacterSelect: (character: Character) => void;
}

const CharacterSearch: React.FC<CharacterSearchProps> = ({ onCharacterSelect }) => {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [filteredCharacters, setFilteredCharacters] = useState<Character[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [isCreateModalVisible, setIsCreateModalVisible] = useState<boolean>(false);
  const [form] = Form.useForm();

  // 初始加载所有角色
  useEffect(() => {
    const loadCharacters = async () => {
      setLoading(true);
      try {
        const characters = await characterService.getAllCharacters();
        // 确保是数组
        setFilteredCharacters(Array.isArray(characters) ? characters : []);
      } catch (error) {
        console.error('加载角色失败:', error);
        // 加载失败时显示空数组
        setFilteredCharacters([]);
      } finally {
        setLoading(false);
      }
    };

    loadCharacters();
  }, []);

  // 显示创建角色模态框
  const showCreateModal = () => {
    setIsCreateModalVisible(true);
  };

  // 隐藏创建角色模态框
  const handleCancel = () => {
    setIsCreateModalVisible(false);
    form.resetFields();
  };

  // 创建角色提交
  const handleCreateSubmit = async (values: any) => {
    try {
      // 构建CharacterCreate对象
      const newCharacter: CharacterCreate = {
        id: values.id,
        name: values.name,
        nameEn: values.nameEn,
        avatar: values.avatar || '',
        description: values.description || '',
        background: values.background || '',
        language: (values.language || '').split(',').map((lang: string) => lang.trim()).filter((lang: string) => lang),
        personality: (values.personality || '').split(',').map((trait: string) => trait.trim()).filter((trait: string) => trait),
        skills: (values.skills || '').split(',').map((skill: string) => skill.trim()).filter((skill: string) => skill)
      };

      // 调用服务创建角色
      await characterService.createCharacter(newCharacter);
      
      // 重新加载角色列表
      const updatedCharacters = await characterService.getAllCharacters();
      setFilteredCharacters(Array.isArray(updatedCharacters) ? updatedCharacters : []);
      
      message.success('角色创建成功！');
      setIsCreateModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('创建角色失败:', error);
      message.error('创建角色失败，请重试');
    }
  };

  // 搜索处理函数
  const handleSearch = async (value: string) => {
    setSearchTerm(value);
    setLoading(true);

    try {
      const result = await characterService.searchCharacters(value);
      // 确保结果格式正确
      if (result && Array.isArray(result.characters)) {
        setFilteredCharacters(result.characters);
      } else {
        setFilteredCharacters([]);
      }
    } catch (error) {
      console.error('搜索角色失败:', error);
      setFilteredCharacters([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1 style={{ textAlign: 'center', marginBottom: '30px' }}>AI角色扮演搜索</h1>
      
      <div style={{ maxWidth: '600px', margin: '0 auto 30px' }}>
        <Search
          placeholder="搜索角色名称（中英文）"
          enterButton={<SearchOutlined />}
          size="large"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          onSearch={handleSearch}
        />
        
        <div style={{ marginTop: '20px', textAlign: 'center' }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            size="large"
            onClick={showCreateModal}
          >
            创建新角色
          </Button>
        </div>
      </div>

      {/* 创建角色模态框 */}
      <Modal
        title="创建新角色"
        open={isCreateModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateSubmit}
        >
          <Row gutter={[16, 16]}>
            <Col span={24}>
              <Form.Item
                label="角色ID（英文，唯一标识）"
                name="id"
                rules={[{ required: true, message: '请输入角色ID' }, { pattern: /^[a-zA-Z0-9-]+$/, message: '角色ID只能包含字母、数字和连字符' }]}
              >
                <AntdInput placeholder="例如：harry-potter" />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={12}>
              <Form.Item
                label="角色名称（中文）"
                name="name"
                rules={[{ required: true, message: '请输入角色中文名称' }]}
              >
                <AntdInput placeholder="例如：哈利波特" />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={12}>
              <Form.Item
                label="角色名称（英文）"
                name="nameEn"
                rules={[{ required: true, message: '请输入角色英文名称' }]}
              >
                <AntdInput placeholder="例如：Harry Potter" />
              </Form.Item>
            </Col>
            
            <Col span={24}>
              <Form.Item
                label="角色头像URL（可选）"
                name="avatar"
              >
                <AntdInput placeholder="输入头像图片的URL地址" />
              </Form.Item>
            </Col>
            
            <Col span={24}>
              <Form.Item
                label="角色简介"
                name="description"
                rules={[{ required: true, message: '请输入角色简介' }]}
              >
                <AntdInput.TextArea rows={2} placeholder="简要描述这个角色" />
              </Form.Item>
            </Col>
            
            <Col span={24}>
              <Form.Item
                label="角色背景（可选）"
                name="background"
              >
                <AntdInput.TextArea rows={3} placeholder="详细描述角色的背景故事" />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={12}>
              <Form.Item
                label="语言能力（用逗号分隔）"
                name="language"
                rules={[{ required: true, message: '请输入角色的语言能力' }]}
              >
                <AntdInput placeholder="例如：中文,英文,日文" />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={12}>
              <Form.Item
                label="性格特点（用逗号分隔）"
                name="personality"
                rules={[{ required: true, message: '请输入角色的性格特点' }]}
              >
                <AntdInput placeholder="例如：勇敢,善良,聪明" />
              </Form.Item>
            </Col>
            
            
            <Col span={24} style={{ textAlign: 'center' }}>
              <Button type="default" onClick={handleCancel} style={{ marginRight: '10px' }}>取消</Button>
              <Button type="primary" htmlType="submit">创建角色</Button>
            </Col>
          </Row>
        </Form>
      </Modal>

      <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: '60px' }}>
            <Spin size="large" />
          </div>
        ) : filteredCharacters.length > 0 ? (
          <Row gutter={[16, 16]}>
            {filteredCharacters.map(character => (
              <Col xs={24} sm={12} md={8} key={character.id}>
                <CharacterCard 
                  character={character} 
                  onSelect={() => onCharacterSelect(character)} 
                />
              </Col>
            ))}
          </Row>
        ) : (
          <Empty
            description="没有找到匹配的角色"
            style={{ padding: '60px 0' }}
          />
        )}
      </div>
    </div>
  );
};

export default CharacterSearch;